package safeCommitter.core.launcher;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.ILaunchesListener2;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.internal.launching.JavaSourceLookupDirector;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMRunner;
import org.eclipse.jdt.launching.VMRunnerConfiguration;

import safeCommitter.core.listener.SCListener;
import safeCommitter.utils.SCUtils;

/**
 * Executes a main method on a new JVM.
 * 
 * 
 * @author Luiz Henrique
 * 
 */
public class SCVMLauncher implements ISCLauncher {

	protected final IJavaProject project;

	public SCVMLauncher(final IJavaProject project) {
		this.project = project;
	}

	public void runClazz(Boolean debug, Boolean ignoreNGXmls,
			final String clazzName, ILaunchesListener2 listener,
			final String... args) throws CoreException {
		ILaunchManager launchManager = DebugPlugin.getDefault()
				.getLaunchManager();
		IVMInstall vmInstall = SCUtils.getVMInstall(project);
		if (vmInstall == null)
			return;
		String launchMode = debug ? ILaunchManager.DEBUG_MODE
				: ILaunchManager.RUN_MODE;
		IVMRunner vmRunner = vmInstall.getVMRunner(launchMode);
		if (vmRunner == null)
			return;
		String[] classPath = SCClasspathComputer.computeClasspath(project);
		VMRunnerConfiguration vmConfig = new VMRunnerConfiguration(clazzName,
				classPath);
		if (args != null) {
			vmConfig.setProgramArguments(args);
		}
		ISourceLocator locator = null;

		if (debug) {
			locator = new JavaSourceLookupDirector();
		}

		ILaunch launch = new Launch(null, launchMode, locator);

		if (!debug) {
			launchManager.addLaunchListener(listener);
		}
		launchManager.addLaunch(launch);
		vmRunner.run(vmConfig, launch, null);

	}

	public void runClazz(final String clazzName, final String... args)
			throws CoreException {
		runClazz(false, false, clazzName, new SCListener(), args);
	}

}
